package com.cn.jinl.service;


import com.cn.jinl.api.IUserRouterService;
import com.cn.jinl.dao.UserRouterMapper;
import com.cn.jinl.domain.UserRouter;
import com.cn.jinl.domain.UserRouterExample;
import com.cn.jinl.utils.CollectionsUtil;
import com.cn.jinl.utils.CommonUtil;
import com.cn.jinl.utils.Constants;
import com.cn.jinl.utils.QueryForm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserRouterServiceImpl implements IUserRouterService {

    @Autowired
    private UserRouterMapper userRouterMapper;

    @Override
    public List<UserRouter> selectUserRouters(QueryForm queryForm) throws Exception {
        UserRouterExample example = new UserRouterExample();
        example.createCriteria().andUserIdEqualTo(queryForm.getUserId()).andStatusEqualTo(Constants.NORMAL_STATUS);
        List<UserRouter> list = userRouterMapper.selectByExample(example);
        return list;
    }

    @Override
    public String addUserRouter(UserRouter userRouter) throws Exception {
        int count = 0;
        String userId = userRouter.getUserId();
        if(StringUtils.isBlank(userId)){
            throw new Exception("addUserRouter userId is null");
        }
        UserRouterExample example = new UserRouterExample();
        example.createCriteria().andUserIdEqualTo(userId);
        userRouterMapper.deleteByExample(example);
        List<UserRouter> userRouters = userRouter.getUserRouters();
        if(CollectionsUtil.isNotEmpty(userRouters)){
            for(UserRouter router : userRouters){
                router.setId(CommonUtil.generateRandomNum("router-"));
                router.setUserId(userId);
            }
            count = userRouterMapper.batchInsertLoginRouter(userRouters);
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public String updateUserRouter(UserRouter userRouter) throws Exception {
        UserRouterExample example = new UserRouterExample();
        example.createCriteria().andIdEqualTo(userRouter.getId());
        int count = userRouterMapper.updateByExampleSelective(userRouter,example);
        return  CommonUtil.outStr(count);
    }

    @Override
    public String deleteUserRouter(String id) throws Exception {
        UserRouterExample example = new UserRouterExample();
        example.createCriteria().andIdEqualTo(id);
        int count = userRouterMapper.deleteByExample(example);
        return  CommonUtil.outStr(count);
    }
}
